package com.xywy.common.util.ble.util;

import java.util.UUID;

import com.xywy.common.util.ble.util.BLEBloodPresureProvider.ChangeReceiver;
import com.xywy.wjk.util.WjkConstant;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
/**
 * 体温ble
 * @author wwl
 *
 */
public class BleTemperatureProvider {
	public static final String TAG = "BleTemperatureProvider";
	
	private BluetoothAdapter mBluetoothAdapter ;
	private BluetoothManager mBluetoothManager;
	private static final long SCAN_PERIOD = 10000;
	boolean mScanning;
	private BluetoothGatt mBluetoothGatt;
	private BluetoothGattService BloodPressureService;
	private static final UUID UUID_TempeServierce = UUID
			.fromString("462D179E-9B11-4131-B69F-D6A0368191F4");
	private static final UUID UUID_GetTempe = UUID
			.fromString("00002a1c-0000-1000-8000-00805f9b34fb");
	private static final UUID UUID_TempeCertification = new UUID(
			(0x2A20L << 32) | 0x1000, 0x800000805f9b34fbL);
	private static final UUID UUID_TempeDescriptor = UUID
			.fromString("00002902-0000-1000-8000-00805f9b34fb");
	
	private static BleTemperatureProvider mTemperUtil;
	
	public final static String ACTION_GATT_CONNECTED = "com.example.bluetooth.temp.ACTION_GATT_CONNECTED";
	public final static String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.temp.ACTION_GATT_DISCONNECTED";
	public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.temp.ACTION_GATT_SERVICES_DISCOVERED";
	public final static String ACTION_DATA_AVAILABLE = "com.example.bluetooth.temp.ACTION_DATA_AVAILABLE";
	public final static String ACTION_READ_CHARACTERISTIC = "com.example.bluetooth.temp.ACTION_READ_CHARACTERISTIC";
	public final static String ACTION_SYSTEMID = "com.example.bluetooth.temp.ACTION_SYSTEMID";// 传递SystemID
	public final static String ACTION_WEIGHT_DATA = "com.example.bluetooth.temp.ACTION_WEIGHT_DATA";// 传递体重数据
	public final static String ACTION_XUEYA_DATA = "com.example.bluetooth.temp.ACTION_XUEYA_DATA";// 传递体重数据
	public final static String EXTRA_DATA = "com.example.bluetooth.temp.EXTRA_DATA";
	public final static String ACTION_WRITE_DATA_AVAILABLE = "com.example.bluetooth.temp.ACTION_WRITE_DATA_AVAILABLE";
	
	private Context context;
	private Intent mIntent = null;
	
	private BleTemperatureProvider(Context context){
		this.context = context;
		initBle();
	}
	
	public static BleTemperatureProvider getInstance(Context context){
		if(mTemperUtil == null){
			mTemperUtil = new BleTemperatureProvider(context);
		}
		return mTemperUtil;
	}
	
	
	/**
	 * 如果要使用蓝牙工具类，必须调用此方法
	 * 
	 * @param context
	 * @return
	 */
	public boolean initBle() {
		initReceiver();
		if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
			Toast.makeText(context, "不支持设备", Toast.LENGTH_SHORT).show();
			return false;
		}
		// Initializes Bluetooth adapter.

		if (mBluetoothManager == null) {
			mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
		}
		if (mBluetoothAdapter == null) {
			mBluetoothAdapter = mBluetoothManager.getAdapter();
		}
		openBLE();
		return true;
	}
	
	/**
	 * 直接打开蓝牙
	 */
	public void openBLE() {

		if (mBluetoothAdapter != null || !mBluetoothAdapter.isEnabled()) {
			// Toast.makeText(context, "正在打开蓝牙", Toast.LENGTH_SHORT).show();
			mBluetoothAdapter.enable();
		}
	}
	
	 BluetoothGattCallback mGattCallBack = new BluetoothGattCallback() {
	     public void onConnectionStateChange(android.bluetooth.BluetoothGatt gatt, int status, int newState) {
	    	 System.out.println("statechange-----");
	    	 switch (newState) {
				case BluetoothProfile.STATE_CONNECTED:
					System.out.println("连接成功");
					sendDataBroadcast(ACTION_GATT_CONNECTED);
					mBluetoothGatt.discoverServices();
					break;
				case BluetoothProfile.STATE_DISCONNECTED:
					
					System.out.println("断开连接");
					sendDataBroadcast(ACTION_GATT_DISCONNECTED);
					if(mIntent != null){
						context.sendBroadcast(mIntent);
						mIntent = null;
					}
					//新家上的
					close();
					break;
			default:
				break;
			}
	     };
	     public void onServicesDiscovered(android.bluetooth.BluetoothGatt gatt, int status) {
	    	 if(status == BluetoothGatt.GATT_SUCCESS){
	    		 if(mBluetoothGatt != null){
	    			 BloodPressureService = mBluetoothGatt
								.getService(UUID_TempeServierce);
	    			 BluetoothGattCharacteristic BloodPressureWriteCharacteristic = BloodPressureService
	    					 .getCharacteristic(UUID_TempeCertification);
	    			 if (BloodPressureWriteCharacteristic != null) {
	    				 BloodPressureWriteCharacteristic
	    				 .setValue("1c304237f1574c35".getBytes());
	    				 mBluetoothGatt
	    				 .writeCharacteristic(BloodPressureWriteCharacteristic);
	    			 }
	    			 sendDataBroadcast(ACTION_GATT_SERVICES_DISCOVERED);
	    		 }
					
	    	 }
	     };
	     
	 	public void onCharacteristicWrite(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic, int status) {
	 		System.out.println("onCharacteristicWrite------------------temp");
	 		sendDataBroadcast(ACTION_WEIGHT_DATA);
		}
	 	
	 	@Override
		public void onCharacteristicChanged(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic) {
	 		 Log.e(TAG, "onCharacteristicChanged");
			if (characteristic.getUuid().equals(UUID_GetTempe)) {
				 Log.e(TAG, "onCharacteristicChanged---uid");
				mBluetoothGatt.readCharacteristic(characteristic);
			}
		};
		
		
		public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
			 Log.e(TAG, "onCharacteristicRead");
			if (UUID_GetTempe.equals(characteristic.getUuid())) {
				int t = (((characteristic.getValue()[1] & 0x000000ff) << 8) | (characteristic
						.getValue()[0] & 0x000000ff));
				Message msg1 = new Message();
	            Bundle b = new Bundle();// 存放数据
	            b.putString("TempratureData",t / 100 + "." + t / 10 % 10 + "°");
	            msg1.setData(b);
				System.out
						.printf(">>>>>>>the value is %02x,%02x  The temprature is %d,"
								+ "((int)characteristic.getValue()[1])=%d,  (int) (characteristic.getValue()[0])=%d   characteristic.getValue().length=%d\n",
								characteristic.getValue()[0],
								characteristic.getValue()[1], t,
								(int) characteristic.getValue()[1],
								(int) (characteristic.getValue()[0]),
								characteristic.getValue().length);
				Intent intent = new Intent(ACTION_XUEYA_DATA);
				intent.putExtra("TempratureData", t / 100 + "." + t / 10 % 10 );
				context.sendBroadcast(intent);
			}
		};

	}; 
	
	public void setCharacteristicNotification(
			BluetoothGattCharacteristic characteristic, boolean enabled) {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			Log.w(TAG, "BluetoothAdapter not initialized");
			return;
		}
		mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
		BluetoothGattDescriptor descriptor = characteristic
				.getDescriptor(UUID_TempeDescriptor);
		descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		mBluetoothGatt.writeDescriptor(descriptor);
	}
	
	/**
	 * 连接体温计
	 * @param context
	 * @param device
	 */
	public void connectTemputer(Context context,BluetoothDevice device){
		mBluetoothGatt = device.connectGatt(context, false, mGattCallBack);
	}
	
	
	
	private void initReceiver(){
		IntentFilter filter = new IntentFilter(WjkConstant.CONNECT_WEIGHT_ACTION_DISCONNECT);
		filter.addAction(WjkConstant.CONNECT_BLOOD_ACTION_DISCONNET);
		context.registerReceiver(new ChangeReceiver(), filter);
	}
	
	class ChangeReceiver extends BroadcastReceiver{
		String tag = "血压 util ChangeReceiver";
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.e(tag, "体温的-------------------------------开始断开连接");
			 if (WjkConstant.CONNECT_WEIGHT_ACTION_DISCONNECT.equals(action)){
				mIntent = new Intent(WjkConstant.DISCONNECT_ACTION_TOWEIGHT);
				disconnect();
			}else if (WjkConstant.CONNECT_BLOOD_ACTION_DISCONNET.equals(action)) {
				mIntent = new Intent(WjkConstant.DISCONNECT_ACTION_TOBLOOD);
				disconnect();
			}
			
		}
	}
	
	/**
	 * Disconnects an existing connection or cancel a pending connection. The
	 * disconnection result is reported asynchronously through the
	 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
	 * callback.
	 */
	public void disconnect() {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			return;
		}
		mBluetoothGatt.disconnect();
//		try {
//			Thread.sleep(20);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		close();
	}

	private void close() {
		if (mBluetoothGatt == null) {
			return;
		}
		mBluetoothGatt.close();
		mBluetoothGatt = null;
	}
	
	private void sendDataBroadcast(String action){
		Intent intent = new Intent(action);
		context.sendBroadcast(intent);
	}
	
	public BluetoothAdapter getAdaper(){
		return mBluetoothAdapter;
	}
	
	/**
	 * 开始测量
	 */
	public void startTest(){
//		if(mBluetoothGatt != null){
//			BluetoothGattService service = mBluetoothGatt.getService(UUID_TempeServierce);
//			if(service != null){
//				setCharacteristicNotification(
//						service
//								.getCharacteristic(UUID_GetTempe), true);
//			}
//		}
		try {
			setCharacteristicNotification(
					mBluetoothGatt.getService(UUID_TempeServierce)
					.getCharacteristic(UUID_GetTempe), true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
}
